﻿using _CUSTOM_CONTROLS._ChatListBox;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
using WindowsFormsForControlTest;

namespace SoftwareManager
{
    public partial class Finder : Form
    {
        private Dictionary<string, List<AppInfo>> AppInfoGroups;

        public Finder()
        {
            InitializeComponent();
            Init();
        }

        private void Init()
        {
            AppInfoGroups = DataManager._Instance.AppInfoGroups;
        }

        #region Events
        private void OnTextChanged(object sender, EventArgs e)
        {
            //获取搜索结果
            List<AppInfo> appInf = new List<AppInfo>();
            foreach (List<AppInfo> infoList in AppInfoGroups.Values)
                foreach (AppInfo af in infoList)
                {
                    bool contains = af.CustomAppName.IndexOf(textBox1.Text,StringComparison.OrdinalIgnoreCase) >= 0;
                    if (contains)
                        if (!appInf.Contains(af))
                            appInf.Add(af);
                }

            if (appInf == null || appInf.Count == 0) return;

            chatListBox1.Items.Clear();

            ChatListItem item = new ChatListItem("搜索结果");
            item.IsOpen = true;

            //显示
            try
            {
                foreach (AppInfo inf in appInf)
                {
                    ChatListSubItem subItem = new ChatListSubItem(inf.CustomAppName, inf.CustomAppName, "");
                    if (!File.Exists("Images/" + inf.CustomAppName + ".png"))
                        subItem.HeadImage = Image.FromFile("Images/default.png");
                    else
                        subItem.HeadImage = Image.FromFile("Images/" + inf.CustomAppName + ".png");
                    item.SubItems.AddAccordingToStatus(subItem);
                }

                item.SubItems.Sort();
                chatListBox1.Items.Add(item);
            }
            catch(Exception message)
            {
                MessageBox.Show(message.Message);
                return;
            }
            
        }

        private void chatListBox1_DoubleClickSubItem(object sender, ChatListEventArgs e)
        {
            string CustomAppName = e.SelectSubItem.NicName;
            AppInfo info = DataManager._Instance.AppSearch(CustomAppName);

            if (info == null || info.FullPath == "") return;
            if (!File.Exists(info.FullPath)) { MessageBox.Show("改程序指定的路径不存在！"); return; };

            Process.Start(info.FullPath);
        }
        #endregion
    }
}
